package cn.jg.framework.common.util.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Objects;

/**
 * json格式序列化/反序列化
 *
 * @author scott he
 * @date 2017/4/17
 */
@Slf4j
public final class JsonHelper {
	private JsonHelper() {
	}

	public static class Deserialize {
		private Deserialize() {
		}

		/**
		 * 反序列化
		 *
		 * @param json          json字符串
		 * @param typeReference 目标类型
		 * @param <T>           ttt
		 * @return rrr
		 */
		public static <T> T convert(String json, TypeReference<T> typeReference) {
			try {
				JsonFactory jsonFactory = new JsonFactory();
				jsonFactory.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
				ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
				objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				return objectMapper.readValue(json, typeReference);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}

	public static class Serialize {
		private Serialize() {
		}

		/**
		 * 序列化
		 *
		 * @param object 待序列化对象
		 * @return rrr
		 */
		public static String convert(Object object) {
			Writer writer = new StringWriter();
			JsonGenerator jsonGenerator = null;
			try {
				JsonFactory jsonFactory = new JsonFactory();
				jsonGenerator = jsonFactory.createGenerator(writer);
				ObjectMapper objectMapper = new ObjectMapper();
				objectMapper.writeValue(jsonGenerator, object);
				writer.flush();
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			} finally {
				if (Objects.nonNull(jsonGenerator)) {
					try {
						jsonGenerator.close();
					} catch (IOException e) {
						log.error("error", e);
					}
				}
			}
			return writer.toString();
		}
	}
}
